<template>
  <div>
    <!-- 加载状态 -->
    <div v-if="loading">加载中...</div>
    
    <!-- 错误提示 -->
    <div v-if="error" class="error">{{ error }}</div>
    
    <!-- 用户列表 -->
    <ul v-if="users.length">
      <li v-for="user in users" :key="user.id">
        {{ user.name }} - {{ user.email }}
      </li>
    </ul>
    
    <!-- 添加用户表单 -->
    <form @submit.prevent="addUser">
      <input v-model="newUser.name" placeholder="姓名" />
      <input v-model="newUser.email" placeholder="邮箱" />
      <button type="submit">添加用户</button>
    </form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import api from '../api/index.js'

// 响应式数据
const users = ref([])
const loading = ref(false)
const error = ref(null)
const newUser = ref({
  name: '',
  email: ''
})

// 获取用户列表
const fetchUsers = async () => {
  try {
    loading.value = true
    const res = await api.get('/users')
    users.value = res.data
  } catch (err) {
    error.value = err.response?.data?.message || '获取用户列表失败'
  } finally {
    loading.value = false
  }
}

// 添加用户
const addUser = async () => {
  try {
    loading.value = true
    const res = await api.post('/users', newUser.value)
    users.value.push(res.data)
    newUser.value = { name: '', email: '' } // 清空表单
  } catch (err) {
    error.value = err.response?.data?.message || '添加用户失败'
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.error {
  color: red;
}
</style>